<template>
  <div class="same-odds-analysis-page">
    <!-- 页面标题 -->
    <el-card class="title-card" shadow="never">
      <div class="page-title">
        <h2>{{ pageTitle }}</h2>
        <el-button type="text" @click="goBack">
          <el-icon><ArrowLeft /></el-icon>
          返回列表
        </el-button>
      </div>
    </el-card>
     <!-- 爆冷分析结果 -->
    <el-card class="cold-play-analysis-card" shadow="never" v-if="coldPlayAnalysisData">
      <template #header>
        <div class="card-header">
          <span>爆冷分析结果</span>
        </div>
      </template>
      
      <div class="cold-play-analysis-content">
        <el-row :gutter="20">
          <!-- 主队爆冷分析 -->
          <el-col :span="12">
            <div class="team-analysis home">
              <h3 class="team-title">主队爆冷分析</h3>
              <el-table 
                :data="[coldPlayAnalysisData.home]" 
                size="small"
                style="width: 100%"
                :show-header="false"
                :cell-style="{ padding: '8px 0' }"
              >
                <el-table-column width="120" label="总比赛场次">
                  <template #default="{ row }">
                    <div class="table-cell">
                      <div class="cell-label">总比赛场次</div>
                      <div class="cell-value">{{ row?.total_matches || 0 }}</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column width="120" label="爆冷场次">
                  <template #default="{ row }">
                    <div class="table-cell">
                      <div class="cell-label">爆冷场次</div>
                      <div class="cell-value">{{ row?.error_matches || 0 }}</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column width="120" label="爆冷率">
                  <template #default="{ row }">
                    <div class="table-cell">
                      <div class="cell-label">爆冷率</div>
                      <div class="cell-value">{{ row?.error_matches_rate ? (row.error_matches_rate * 100).toFixed(2) : '0.00' }}%</div>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-col>
          
          <!-- 客队爆冷分析 -->
          <el-col :span="12">
            <div class="team-analysis away">
              <h3 class="team-title">客队爆冷分析</h3>
              <el-table 
                :data="[coldPlayAnalysisData.away]" 
                size="small"
                style="width: 100%"
                :show-header="false"
                :cell-style="{ padding: '8px 0' }"
              >
                <el-table-column width="120" label="总比赛场次">
                  <template #default="{ row }">
                    <div class="table-cell">
                      <div class="cell-label">总比赛场次</div>
                      <div class="cell-value">{{ row?.total_matches || 0 }}</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column width="120" label="爆冷场次">
                  <template #default="{ row }">
                    <div class="table-cell">
                      <div class="cell-label">爆冷场次</div>
                      <div class="cell-value">{{ row?.error_matches || 0 }}</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column width="120" label="爆冷率">
                  <template #default="{ row }">
                    <div class="table-cell">
                      <div class="cell-label">爆冷率</div>
                      <div class="cell-value">{{ row?.error_matches_rate ? (row.error_matches_rate * 100).toFixed(2) : '0.00' }}%</div>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 上半部分：赔率范围设置 -->
    <el-card class="odds-range-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>赔率范围设置</span>
          <div class="card-header-actions">
            <el-button type="primary" size="small" @click="resetRangeInputs">重置范围</el-button>
          </div>
        </div>
      </template>
      
      <div class="odds-range-content">
        <!-- 赔率范围调节器 -->
        <el-row :gutter="20" class="volatility-row">
          <el-col :span="8">
            <div class="volatility-control">
              <h4>主队赔率范围调节</h4>
              <div class="volatility-info" v-if="selectedMatchOdds.home.length > 0">
                <div class="volatility-range">
                  变化率: {{ (getVolatilityRate(selectedMatchOdds.home) * 100).toFixed(2) }}%
                </div>
              </div>
              <div class="volatility-stepper">
                <span class="volatility-label">波动率:</span>
                <el-button 
                  :icon="Minus" 
                  circle 
                  size="small"
                  @click="adjustVolatility('home', -0.5)"
                  :disabled="homeVolatility <= 1"
                />
                <span class="volatility-value">{{ homeVolatility.toFixed(2) }}%</span>
                <el-button 
                  :icon="Plus" 
                  circle 
                  size="small"
                  @click="adjustVolatility('home', 0.5)"
                  :disabled="homeVolatility >= 20"
                />
              </div>
            </div>
          </el-col>
          
          <el-col :span="8">
            <div class="volatility-control">
              <h4>平局赔率范围调节</h4>
              <div class="volatility-info" v-if="selectedMatchOdds.draw.length > 0">
                <div class="volatility-range">
                  变化率: {{ (getVolatilityRate(selectedMatchOdds.draw) * 100).toFixed(2) }}%
                </div>
              </div>
              <div class="volatility-stepper">
                <span class="volatility-label">波动率:</span>
                <el-button 
                  :icon="Minus" 
                  circle 
                  size="small"
                  @click="adjustVolatility('draw', -0.5)"
                  :disabled="drawVolatility <= 1"
                />
                <span class="volatility-value">{{ drawVolatility.toFixed(2) }}%</span>
                <el-button 
                  :icon="Plus" 
                  circle 
                  size="small"
                  @click="adjustVolatility('draw', 0.5)"
                  :disabled="drawVolatility >= 20"
                />
              </div>
            </div>
          </el-col>
          
          <el-col :span="8">
            <div class="volatility-control">
              <h4>客队赔率范围调节</h4>
              <div class="volatility-info" v-if="selectedMatchOdds.away.length > 0">
                <div class="volatility-range">
                  变化率: {{ (getVolatilityRate(selectedMatchOdds.away) * 100).toFixed(2) }}%
                </div>
              </div>
              <div class="volatility-stepper">
                <span class="volatility-label">波动率:</span>
                <el-button 
                  :icon="Minus" 
                  circle 
                  size="small"
                  @click="adjustVolatility('away', -0.5)"
                  :disabled="awayVolatility <= 1"
                />
                <span class="volatility-value">{{ awayVolatility.toFixed(2) }}%</span>
                <el-button 
                  :icon="Plus" 
                  circle 
                  size="small"
                  @click="adjustVolatility('away', 0.5)"
                  :disabled="awayVolatility >= 20"
                />
              </div>
            </div>
          </el-col>
        </el-row>

        <el-divider />

        

        <!-- 赔率范围显示 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <h4>主队赔率范围</h4>
            <div class="odds-range-item" v-for="(odds, index) in selectedMatchOdds.home" :key="`home-${index}`">
              <span class="odds-label">{{ odds.label }}:</span>
              <span class="odds-value">{{ odds.value?.toFixed(3) || '-' }}</span>
              <span class="odds-range">({{ odds.min?.toFixed(3) || '-' }} - {{ odds.max?.toFixed(3) || '-' }})</span>
            </div>
          </el-col>
          
          <el-col :span="8">
            <h4>平局赔率范围</h4>
            <div class="odds-range-item" v-for="(odds, index) in selectedMatchOdds.draw" :key="`draw-${index}`">
              <span class="odds-label">{{ odds.label }}:</span>
              <span class="odds-value">{{ odds.value?.toFixed(3) || '-' }}</span>
              <span class="odds-range">({{ odds.min?.toFixed(3) || '-' }} - {{ odds.max?.toFixed(3) || '-' }})</span>
            </div>
          </el-col>
          
          <el-col :span="8">
            <h4>客队赔率范围</h4>
            <div class="odds-range-item" v-for="(odds, index) in selectedMatchOdds.away" :key="`away-${index}`">
              <span class="odds-label">{{ odds.label }}:</span>
              <span class="odds-value">{{ odds.value?.toFixed(3) || '-' }}</span>
              <span class="odds-range">({{ odds.min?.toFixed(3) || '-' }} - {{ odds.max?.toFixed(3) || '-' }})</span>
            </div>
          </el-col>
        </el-row>
        <!-- 积分和信号值范围设置 -->
        <el-row :gutter="20" class="range-inputs-row">
          <!-- 主队积分范围 -->
          <el-col :span="4">
            <div class="range-input-group compact">
              <h4>主队积分</h4>
              <el-row :gutter="10">
                <el-col :span="11">
                  <el-input-number 
                    v-model="homeAvgPointsMin" 
                    placeholder="最小值" 
                    :precision="2" 
                    :step="0.1" 
                    size="small" 
                    style="width: 100%"
                  />
                </el-col>
               
                <el-col :span="11">
                  <el-input-number 
                    v-model="homeAvgPointsMax" 
                    placeholder="最大值" 
                    :precision="2" 
                    :step="0.1" 
                    size="small" 
                    style="width: 100%"
                  />
                </el-col>
              </el-row>
            </div>
          </el-col>
          
          <!-- 客队积分范围 -->
          <el-col :span="4">
            <div class="range-input-group compact">
              <h4>客队积分</h4>
              <el-row :gutter="10">
                <el-col :span="11">
                  <el-input-number 
                    v-model="awayAvgPointsMin" 
                    placeholder="最小值" 
                    :precision="2" 
                    :step="0.1" 
                    size="small" 
                    style="width: 100%"
                  />
                </el-col>
                
                <el-col :span="11">
                  <el-input-number 
                    v-model="awayAvgPointsMax" 
                    placeholder="最大值" 
                    :precision="2" 
                    :step="0.1" 
                    size="small" 
                    style="width: 100%"
                  />
                </el-col>
              </el-row>
            </div>
          </el-col>
          
          <!-- 主队信号值范围 -->
          <el-col :span="5">
            <div class="range-input-group compact">
              <h4>主队信号</h4>
              <el-row :gutter="10">
                <el-col :span="11">
                  <el-input-number 
                    v-model="signalHomeMin" 
                    placeholder="最小" 
                    :precision="2" 
                    :step="0.1" 
                    size="small" 
                    style="width: 100%"
                  />
                </el-col>
               
                <el-col :span="11">
                  <el-input-number 
                    v-model="signalHomeMax" 
                    placeholder="最大" 
                    :precision="2" 
                    :step="0.1" 
                    size="small" 
                    style="width: 100%"
                  />
                </el-col>
              </el-row>
            </div>
          </el-col>
          
          <!-- 平局信号值范围 -->
          <el-col :span="5">
            <div class="range-input-group compact">
              <h4>平局信号</h4>
              <el-row :gutter="10">
                <el-col :span="11">
                  <el-input-number 
                    v-model="signalDrawMin" 
                    placeholder="最小" 
                    :precision="2" 
                    :step="0.1" 
                    size="small" 
                    style="width: 100%"
                  />
                </el-col>
               
                <el-col :span="11">
                  <el-input-number 
                    v-model="signalDrawMax" 
                    placeholder="最大" 
                    :precision="2" 
                    :step="0.1" 
                    size="small" 
                    style="width: 100%"
                  />
                </el-col>
              </el-row>
            </div>
          </el-col>
          
          <!-- 客队信号值范围 -->
          <el-col :span="5">
            <div class="range-input-group compact">
              <h4>客队信号</h4>
              <el-row :gutter="10">
                <el-col :span="11">
                  <el-input-number 
                    v-model="signalAwayMin" 
                    placeholder="最小" 
                    :precision="2" 
                    :step="0.1" 
                    size="small" 
                    style="width: 100%"
                  />
                </el-col>
               <el-col :span="11">
                  <el-input-number 
                    v-model="signalAwayMax" 
                    placeholder="最大" 
                    :precision="2" 
                    :step="0.1" 
                    size="small" 
                    style="width: 100%"
                  />
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>
        <div class="query-button-wrapper">
          <el-button 
            type="primary" 
            size="large" 
            @click="querySameOddsAnalysis"
            :loading="sameOddsAnalysisLoading"
          >
            <el-icon><Search /></el-icon>
            查询同赔
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 下半部分：同赔分析结果 -->
    <el-card class="analysis-result-card" shadow="never" v-if="sameOddsAnalysisResult">
      <template #header>
        <div class="card-header">
          <span>同赔分析结果</span>
        </div>
      </template>
      
      <div class="analysis-result-content">
        <!-- 统计信息 -->
        <el-row :gutter="20" class="stats-row">
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ sameOddsAnalysisResult.total_matches }}</div>
              <div class="stat-label">总比赛场次</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ sameOddsAnalysisResult.home_wins }}</div>
              <div class="stat-label">主胜场次</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ sameOddsAnalysisResult.draws }}</div>
              <div class="stat-label">平局场次</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ sameOddsAnalysisResult.away_wins }}</div>
              <div class="stat-label">客胜场次</div>
            </div>
          </el-col>
        </el-row>
        
        <!-- 胜率分析 -->
        <el-row :gutter="20" class="rate-row">
          <el-col :span="8">
            <div class="rate-item home">
              <div class="rate-value">{{ sameOddsAnalysisResult.home_win_rate?.toFixed(2) || '0.00' }}%</div>
              <div class="rate-label">主胜率</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="rate-item draw">
              <div class="rate-value">{{ sameOddsAnalysisResult.draw_rate?.toFixed(2) || '0.00' }}%</div>
              <div class="rate-label">平局率</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="rate-item away">
              <div class="rate-value">{{ sameOddsAnalysisResult.away_win_rate?.toFixed(2) || '0.00' }}%</div>
              <div class="rate-label">客胜率</div>
            </div>
          </el-col>
        </el-row>
        
        <!-- 常见比分 -->
        <el-row :gutter="20" class="score-row">
          <el-col :span="8">
            <div class="score-item">
              <div class="score-label">最常见比分</div>
              <div class="score-value">{{ sameOddsAnalysisResult.most_common_score || '-' }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="score-item">
              <div class="score-label">第二常见比分</div>
              <div class="score-value">{{ sameOddsAnalysisResult.second_most_common_score || '-' }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="score-item">
              <div class="score-label">第三常见比分</div>
              <div class="score-value">{{ sameOddsAnalysisResult.third_most_common_score || '-' }}</div>
            </div>
          </el-col>
        </el-row>
        
        <!-- 主胜常见比分 -->
        <el-row :gutter="20" class="score-row">
          <el-col :span="8">
            <div class="score-item">
              <div class="score-label">主胜最常见比分</div>
              <div class="score-value">{{ sameOddsAnalysisResult.home_win_most_common_score || '-' }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="score-item">
              <div class="score-label">主胜第二常见比分</div>
              <div class="score-value">{{ sameOddsAnalysisResult.home_win_second_most_common_score || '-' }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="score-item">
              <div class="score-label">主胜第三常见比分</div>
              <div class="score-value">{{ sameOddsAnalysisResult.home_win_third_most_common_score || '-' }}</div>
            </div>
          </el-col>
        </el-row>
        
        <!-- 客胜常见比分 -->
        <el-row :gutter="20" class="score-row">
          <el-col :span="8">
            <div class="score-item">
              <div class="score-label">客胜最常见比分</div>
              <div class="score-value">{{ sameOddsAnalysisResult.away_win_most_common_score || '-' }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="score-item">
              <div class="score-label">客胜第二常见比分</div>
              <div class="score-value">{{ sameOddsAnalysisResult.away_win_second_most_common_score || '-' }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="score-item">
              <div class="score-label">客胜第三常见比分</div>
              <div class="score-value">{{ sameOddsAnalysisResult.away_win_third_most_common_score || '-' }}</div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>
    
    <!-- 符合条件的比赛明细表格 -->
    <el-card class="match-details-card" shadow="never" v-if="sameOddsAnalysisResult">
      <template #header>
        <div class="card-header">
          <span>符合条件的比赛明细</span>
        </div>
      </template>
      
      <el-table 
        :data="matchDetailsData" 
        v-loading="matchDetailsLoading"
        stripe
        style="width: 100%"
        height="400"
      >
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="event_name" label="赛事名称" min-width="80" />
        <el-table-column prop="order_num" label="赛事编号" min-width="80" />
        <el-table-column prop="matchtime" label="比赛时间" min-width="90" />
        <el-table-column prop="homesxname" label="主队" min-width="90" />
        <el-table-column prop="awaysxname" label="客队" min-width="90" />
        <el-table-column prop="homescore" label="主队得分" min-width="50" />
        <el-table-column prop="awayscore" label="客队得分" min-width="50" />
        <el-table-column prop="home_avg_points" label="主队积分" min-width="80" />
        <el-table-column prop="away_avg_points" label="客队积分" min-width="80" />
        <el-table-column prop="signal_home_initial" label="主队信号值" min-width="90" />
        <el-table-column prop="signal_draw_initial" label="平局信号值" min-width="90" />
        <el-table-column prop="signal_away_initial" label="客队信号值" min-width="90" />
        
        <!-- 初始赔率 -->
        <el-table-column label="初始赔率" min-width="150">
          <template #default="{ row }">
            <div class="odds-group">
              <span class="odds-item home">{{ formatOdds(row.home_odds_0) }}</span>
              <span class="odds-item draw">{{ formatOdds(row.draw_odds_0) }}</span>
              <span class="odds-item away">{{ formatOdds(row.away_odds_0) }}</span>
            </div>
          </template>
        </el-table-column>
        
        <!-- 24小时赔率 -->
        <el-table-column label="24小时赔率" min-width="150">
          <template #default="{ row }">
            <div class="odds-group">
              <span class="odds-item home">{{ formatOdds(row.home_odds_24) }}</span>
              <span class="odds-item draw">{{ formatOdds(row.draw_odds_24) }}</span>
              <span class="odds-item away">{{ formatOdds(row.away_odds_24) }}</span>
            </div>
          </template>
        </el-table-column>
        
        <!-- 48小时赔率 -->
        <el-table-column label="48小时赔率" min-width="150">
          <template #default="{ row }">
            <div class="odds-group">
              <span class="odds-item home">{{ formatOdds(row.home_odds_48) }}</span>
              <span class="odds-item draw">{{ formatOdds(row.draw_odds_48) }}</span>
              <span class="odds-item away">{{ formatOdds(row.away_odds_48) }}</span>
            </div>
          </template>
        </el-table-column>
        
        <!-- 72小时赔率 -->
        <el-table-column label="72小时赔率" min-width="150">
          <template #default="{ row }">
            <div class="odds-group">
              <span class="odds-item home">{{ formatOdds(row.home_odds_72) }}</span>
              <span class="odds-item draw">{{ formatOdds(row.draw_odds_72) }}</span>
              <span class="odds-item away">{{ formatOdds(row.away_odds_72) }}</span>
            </div>
          </template>
        </el-table-column>
        
        <!-- 167小时赔率 -->
        <el-table-column label="167小时赔率" min-width="150">
          <template #default="{ row }">
            <div class="odds-group">
              <span class="odds-item home">{{ formatOdds(row.home_odds_167) }}</span>
              <span class="odds-item draw">{{ formatOdds(row.draw_odds_167) }}</span>
              <span class="odds-item away">{{ formatOdds(row.away_odds_167) }}</span>
            </div>
          </template>
        </el-table-column>
        
        <!-- 删除按钮 -->
        <el-table-column label="操作" width="80" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="danger" 
              size="small" 
              @click="removeMatch(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
   
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import type { HistoricalSameOddsData, SameOdds168AnalysisStats, ColdPlayAnalysisStats } from './apis/type'
import { getColdPlayAnalysisStatsApi, getSameOddsMatchDetailsApi } from './apis'
import { Search, ArrowLeft, Minus, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useTagsViewStore } from '@/pinia/stores/tags-view'

const router = useRouter()
const route = useRoute()
const tagsViewStore = useTagsViewStore()

// 响应式数据
const sameOddsAnalysisLoading = ref(false)
const sameOddsAnalysisResult = ref<SameOdds168AnalysisStats | null>(null)
const currentMatchForAnalysis = ref<HistoricalSameOddsData | null>(null)
const coldPlayAnalysisData = ref<{
  home: ColdPlayAnalysisStats | null,
  away: ColdPlayAnalysisStats | null
} | null>(null)
const coldPlayAnalysisLoading = ref(false)

// 比赛明细数据
const matchDetailsData = ref<HistoricalSameOddsData[]>([])
const matchDetailsLoading = ref(false)

// 赔率波动率控制
const homeVolatility = ref(0)
const drawVolatility = ref(0)
const awayVolatility = ref(0)

// 积分范围控制
const homeAvgPointsMin = ref<number | null>(null)
const homeAvgPointsMax = ref<number | null>(null)
const awayAvgPointsMin = ref<number | null>(null)
const awayAvgPointsMax = ref<number | null>(null)

// 信号值范围控制
const signalHomeMin = ref<number | null>(null)
const signalHomeMax = ref<number | null>(null)
const signalDrawMin = ref<number | null>(null)
const signalDrawMax = ref<number | null>(null)
const signalAwayMin = ref<number | null>(null)
const signalAwayMax = ref<number | null>(null)

// 页面标题
const pageTitle = computed(() => {
  if (!currentMatchForAnalysis.value) return '同赔分析'
  const match = currentMatchForAnalysis.value
  const homeScore = match.homescore !== null ? match.homescore : '-'
  const awayScore = match.awayscore !== null ? match.awayscore : '-'
  return `${match.homesxname} ${homeScore} - ${awayScore} ${match.awaysxname}`
})

// 计算选中的比赛赔率范围（使用动态波动率）
const selectedMatchOdds = computed(() => {
  if (!currentMatchForAnalysis.value) {
    return { home: [], draw: [], away: [] }
  }
  
  const match = currentMatchForAnalysis.value
  
  const calculateRange = (value: number | null, volatility: number) => {
    if (value === null) return { value: null, min: null, max: null }
    const volatilityDecimal = volatility / 100
    return {
      value,
      min: value * (1 - volatilityDecimal),
      max: value * (1 + volatilityDecimal)
    }
  }
  
  return {
    home: [
      { label: '初始赔率', ...calculateRange(match.home_odds_0, homeVolatility.value) },
      { label: '24小时赔率', ...calculateRange(match.home_odds_24, homeVolatility.value) },
      { label: '48小时赔率', ...calculateRange(match.home_odds_48, homeVolatility.value) },
      { label: '72小时赔率', ...calculateRange(match.home_odds_72, homeVolatility.value) },
      { label: '168小时赔率', ...calculateRange(match.home_odds_167, homeVolatility.value) }
    ],
    draw: [
      { label: '初始赔率', ...calculateRange(match.draw_odds_0, drawVolatility.value) },
      { label: '24小时赔率', ...calculateRange(match.draw_odds_24, drawVolatility.value) },
      { label: '48小时赔率', ...calculateRange(match.draw_odds_48, drawVolatility.value) },
      { label: '72小时赔率', ...calculateRange(match.draw_odds_72, drawVolatility.value) },
      { label: '168小时赔率', ...calculateRange(match.draw_odds_167, drawVolatility.value) }
    ],
    away: [
      { label: '初始赔率', ...calculateRange(match.away_odds_0, awayVolatility.value) },
      { label: '24小时赔率', ...calculateRange(match.away_odds_24, awayVolatility.value) },
      { label: '48小时赔率', ...calculateRange(match.away_odds_48, awayVolatility.value) },
      { label: '72小时赔率', ...calculateRange(match.away_odds_72, awayVolatility.value) },
      { label: '168小时赔率', ...calculateRange(match.away_odds_167, awayVolatility.value) }
    ]
  }
})

// 方法
function goBack() {
  router.push('/odds/same-europe-168')
}

// 格式化赔率显示
function formatOdds(value: number | null | undefined): string {
  if (value === null || value === undefined) {
    return '-'
  }
  // 保留3位小数
  return value.toFixed(3)
}

// 删除比赛并重新计算同赔分析结果
function removeMatch(row: HistoricalSameOddsData) {
  // 从matchDetailsData中移除该行
  const index = matchDetailsData.value.findIndex(item => item.fid === row.fid);
  if (index !== -1) {
    matchDetailsData.value.splice(index, 1);
    
    // 重新计算同赔分析结果
    recalculateSameOddsAnalysis();
  }
}

// 重新计算同赔分析结果
function recalculateSameOddsAnalysis() {
  const data = matchDetailsData.value;
  const total_matches = data.length;
  let home_wins = 0;
  let draws = 0;
  let away_wins = 0;
  
  // 用于统计比分出现次数
  const scoreCounts: Record<string, number> = {};
  const homeWinScoreCounts: Record<string, number> = {}; // 主胜比分统计
  const awayWinScoreCounts: Record<string, number> = {}; // 客胜比分统计
  
  // 遍历所有比赛数据进行统计
  for (const match of data) {
    // 统计胜负平结果
    if (match.homescore !== null && match.awayscore !== null) {
      const score = `${match.homescore}-${match.awayscore}`;
      scoreCounts[score] = (scoreCounts[score] || 0) + 1;
      
      if (match.homescore > match.awayscore) {
        home_wins++;
        // 主胜比分统计
        homeWinScoreCounts[score] = (homeWinScoreCounts[score] || 0) + 1;
      } else if (match.homescore === match.awayscore) {
        draws++;
      } else {
        away_wins++;
        // 客胜比分统计
        awayWinScoreCounts[score] = (awayWinScoreCounts[score] || 0) + 1;
      }
    }
  }
  
  // 计算胜率
  const home_win_rate = total_matches > 0 ? (home_wins / total_matches) * 100 : 0;
  const draw_rate = total_matches > 0 ? (draws / total_matches) * 100 : 0;
  const away_win_rate = total_matches > 0 ? (away_wins / total_matches) * 100 : 0;
  
  // 找出最常见的三个比分
  const sortedScores = Object.entries(scoreCounts)
    .sort((a, b) => b[1] - a[1]);
  
  const most_common_score = sortedScores[0] ? sortedScores[0][0] : null;
  const second_most_common_score = sortedScores[1] ? sortedScores[1][0] : null;
  const third_most_common_score = sortedScores[2] ? sortedScores[2][0] : null;
  
  // 找出主胜的三个常见比分
  const sortedHomeWinScores = Object.entries(homeWinScoreCounts)
    .sort((a, b) => b[1] - a[1]);
  
  const home_win_most_common_score = sortedHomeWinScores[0] ? sortedHomeWinScores[0][0] : null;
  const home_win_second_most_common_score = sortedHomeWinScores[1] ? sortedHomeWinScores[1][0] : null;
  const home_win_third_most_common_score = sortedHomeWinScores[2] ? sortedHomeWinScores[2][0] : null;
  
  // 找出客胜的三个常见比分
  const sortedAwayWinScores = Object.entries(awayWinScoreCounts)
    .sort((a, b) => b[1] - a[1]);
  
  const away_win_most_common_score = sortedAwayWinScores[0] ? sortedAwayWinScores[0][0] : null;
  const away_win_second_most_common_score = sortedAwayWinScores[1] ? sortedAwayWinScores[1][0] : null;
  const away_win_third_most_common_score = sortedAwayWinScores[2] ? sortedAwayWinScores[2][0] : null;
  
  // 更新同赔分析结果
  sameOddsAnalysisResult.value = {
    total_matches,
    home_wins,
    draws,
    away_wins,
    home_win_rate,
    draw_rate,
    away_win_rate,
    most_common_score,
    second_most_common_score,
    third_most_common_score,
    home_win_most_common_score,
    home_win_second_most_common_score,
    home_win_third_most_common_score,
    away_win_most_common_score,
    away_win_second_most_common_score,
    away_win_third_most_common_score
  };
}

// 重置范围输入
function resetRangeInputs() {
  // 重置积分范围
  homeAvgPointsMin.value = null
  homeAvgPointsMax.value = null
  awayAvgPointsMin.value = null
  awayAvgPointsMax.value = null
  
  // 重置信号值范围
  signalHomeMin.value = null
  signalHomeMax.value = null
  signalDrawMin.value = null
  signalDrawMax.value = null
  signalAwayMin.value = null
  signalAwayMax.value = null
}

// 更新赔率范围（由于使用了计算属性，这个方法可以是空的）
function updateOddsRanges() {
  // 计算属性会自动更新，这里不需要额外操作
}

// 调整波动率
function adjustVolatility(type: 'home' | 'draw' | 'away', delta: number) {
  switch (type) {
    case 'home':
      homeVolatility.value = Math.max(1, Math.min(20, homeVolatility.value + delta))
      break
    case 'draw':
      drawVolatility.value = Math.max(1, Math.min(20, drawVolatility.value + delta))
      break
    case 'away':
      awayVolatility.value = Math.max(1, Math.min(20, awayVolatility.value + delta))
      break
  }
}

// 计算最大变化率
function getMaxVolatility(oddsArray: Array<{ value: number | null; min: number | null; max: number | null }>): number {
  let maxVolatility = 0
  for (const odds of oddsArray) {
    if (odds.value && odds.min) {
      const volatility = ((odds.value - odds.min) / odds.value) * 100
      if (volatility > maxVolatility) {
        maxVolatility = volatility
      }
    }
  }
  return maxVolatility
}

// 计算最小变化率
function getMinVolatility(oddsArray: Array<{ value: number | null; min: number | null; max: number | null }>): number {
  let minVolatility = Infinity
  for (const odds of oddsArray) {
    if (odds.value && odds.min) {
      const volatility = ((odds.value - odds.min) / odds.value) * 100
      if (volatility < minVolatility) {
        minVolatility = volatility
      }
    }
  }
  return isFinite(minVolatility) ? minVolatility : 0
}

// 计算变化率（最大值/最小值-1）
function getVolatilityRate(oddsArray: Array<{ value: number | null; min: number | null; max: number | null }>): number {
  let maxValue: number | null = null
  let minValue: number | null = null
  
  // 找到所有赔率中的最大值和最小值
  for (const odds of oddsArray) {
    if (odds.value !== null) {
      if (maxValue === null || odds.value > maxValue) {
        maxValue = odds.value
      }
      if (minValue === null || odds.value < minValue) {
        minValue = odds.value
      }
    }
  }
  
  // 如果没有有效数据，返回0
  if (maxValue === null || minValue === null || minValue === 0) {
    return 0
  }
  
  // 计算变化率：最大值/最小值-1
  return (maxValue / minValue) - 1
}

// 查询同赔分析
async function querySameOddsAnalysis() {
  if (!currentMatchForAnalysis.value) {
    ElMessage.error('请先选择比赛')
    return
  }
  
  sameOddsAnalysisLoading.value = true
  coldPlayAnalysisLoading.value = true
  matchDetailsLoading.value = true
  
  try {
    // 使用传入的波动率
    const homeVol = homeVolatility.value / 100
    const drawVol = drawVolatility.value / 100
    const awayVol = awayVolatility.value / 100
    
    const match = currentMatchForAnalysis.value
    
    // 构造请求参数
    const requestData = {
      event_name: match.event_name || null,
      matchtime_max: match.matchtime ? match.matchtime.split('T')[0] : null,
      
      // 主队赔率范围
      home_odds_0_min: match.home_odds_0 !== null ? match.home_odds_0 * (1 - homeVol) : null,
      home_odds_0_max: match.home_odds_0 !== null ? match.home_odds_0 * (1 + homeVol) : null,
      home_odds_24_min: match.home_odds_24 !== null ? match.home_odds_24 * (1 - homeVol) : null,
      home_odds_24_max: match.home_odds_24 !== null ? match.home_odds_24 * (1 + homeVol) : null,
      home_odds_48_min: match.home_odds_48 !== null ? match.home_odds_48 * (1 - homeVol) : null,
      home_odds_48_max: match.home_odds_48 !== null ? match.home_odds_48 * (1 + homeVol) : null,
      home_odds_72_min: match.home_odds_72 !== null ? match.home_odds_72 * (1 - homeVol) : null,
      home_odds_72_max: match.home_odds_72 !== null ? match.home_odds_72 * (1 + homeVol) : null,
      home_odds_167_min: match.home_odds_167 !== null ? match.home_odds_167 * (1 - homeVol) : null,
      home_odds_167_max: match.home_odds_167 !== null ? match.home_odds_167 * (1 + homeVol) : null,
      
      // 平局赔率范围
      draw_odds_0_min: match.draw_odds_0 !== null ? match.draw_odds_0 * (1 - drawVol) : null,
      draw_odds_0_max: match.draw_odds_0 !== null ? match.draw_odds_0 * (1 + drawVol) : null,
      draw_odds_24_min: match.draw_odds_24 !== null ? match.draw_odds_24 * (1 - drawVol) : null,
      draw_odds_24_max: match.draw_odds_24 !== null ? match.draw_odds_24 * (1 + drawVol) : null,
      draw_odds_48_min: match.draw_odds_48 !== null ? match.draw_odds_48 * (1 - drawVol) : null,
      draw_odds_48_max: match.draw_odds_48 !== null ? match.draw_odds_48 * (1 + drawVol) : null,
      draw_odds_72_min: match.draw_odds_72 !== null ? match.draw_odds_72 * (1 - drawVol) : null,
      draw_odds_72_max: match.draw_odds_72 !== null ? match.draw_odds_72 * (1 + drawVol) : null,
      draw_odds_167_min: match.draw_odds_167 !== null ? match.draw_odds_167 * (1 - drawVol) : null,
      draw_odds_167_max: match.draw_odds_167 !== null ? match.draw_odds_167 * (1 + drawVol) : null,
      
      // 客队赔率范围
      away_odds_0_min: match.away_odds_0 !== null ? match.away_odds_0 * (1 - awayVol) : null,
      away_odds_0_max: match.away_odds_0 !== null ? match.away_odds_0 * (1 + awayVol) : null,
      away_odds_24_min: match.away_odds_24 !== null ? match.away_odds_24 * (1 - awayVol) : null,
      away_odds_24_max: match.away_odds_24 !== null ? match.away_odds_24 * (1 + awayVol) : null,
      away_odds_48_min: match.away_odds_48 !== null ? match.away_odds_48 * (1 - awayVol) : null,
      away_odds_48_max: match.away_odds_48 !== null ? match.away_odds_48 * (1 + awayVol) : null,
      away_odds_72_min: match.away_odds_72 !== null ? match.away_odds_72 * (1 - awayVol) : null,
      away_odds_72_max: match.away_odds_72 !== null ? match.away_odds_72 * (1 + awayVol) : null,
      away_odds_167_min: match.away_odds_167 !== null ? match.away_odds_167 * (1 - awayVol) : null,
      away_odds_167_max: match.away_odds_167 !== null ? match.away_odds_167 * (1 + awayVol) : null
    }
    
    // 构造同赔分析请求参数
    const sameOddsRequestData = {
      event_name: match.event_name || null,
      matchtime_max: match.matchtime ? match.matchtime.split('T')[0] : null,
      
      // 主队赔率范围
      home_odds_0_min: match.home_odds_0 !== null ? match.home_odds_0 * (1 - homeVol) : null,
      home_odds_0_max: match.home_odds_0 !== null ? match.home_odds_0 * (1 + homeVol) : null,
      home_odds_24_min: match.home_odds_24 !== null ? match.home_odds_24 * (1 - homeVol) : null,
      home_odds_24_max: match.home_odds_24 !== null ? match.home_odds_24 * (1 + homeVol) : null,
      home_odds_48_min: match.home_odds_48 !== null ? match.home_odds_48 * (1 - homeVol) : null,
      home_odds_48_max: match.home_odds_48 !== null ? match.home_odds_48 * (1 + homeVol) : null,
      home_odds_72_min: match.home_odds_72 !== null ? match.home_odds_72 * (1 - homeVol) : null,
      home_odds_72_max: match.home_odds_72 !== null ? match.home_odds_72 * (1 + homeVol) : null,
      home_odds_167_min: match.home_odds_167 !== null ? match.home_odds_167 * (1 - homeVol) : null,
      home_odds_167_max: match.home_odds_167 !== null ? match.home_odds_167 * (1 + homeVol) : null,
      
      // 平局赔率范围
      draw_odds_0_min: match.draw_odds_0 !== null ? match.draw_odds_0 * (1 - drawVol) : null,
      draw_odds_0_max: match.draw_odds_0 !== null ? match.draw_odds_0 * (1 + drawVol) : null,
      draw_odds_24_min: match.draw_odds_24 !== null ? match.draw_odds_24 * (1 - drawVol) : null,
      draw_odds_24_max: match.draw_odds_24 !== null ? match.draw_odds_24 * (1 + drawVol) : null,
      draw_odds_48_min: match.draw_odds_48 !== null ? match.draw_odds_48 * (1 - drawVol) : null,
      draw_odds_48_max: match.draw_odds_48 !== null ? match.draw_odds_48 * (1 + drawVol) : null,
      draw_odds_72_min: match.draw_odds_72 !== null ? match.draw_odds_72 * (1 - drawVol) : null,
      draw_odds_72_max: match.draw_odds_72 !== null ? match.draw_odds_72 * (1 + drawVol) : null,
      draw_odds_167_min: match.draw_odds_167 !== null ? match.draw_odds_167 * (1 - drawVol) : null,
      draw_odds_167_max: match.draw_odds_167 !== null ? match.draw_odds_167 * (1 + drawVol) : null,
      
      // 客队赔率范围
      away_odds_0_min: match.away_odds_0 !== null ? match.away_odds_0 * (1 - awayVol) : null,
      away_odds_0_max: match.away_odds_0 !== null ? match.away_odds_0 * (1 + awayVol) : null,
      away_odds_24_min: match.away_odds_24 !== null ? match.away_odds_24 * (1 - awayVol) : null,
      away_odds_24_max: match.away_odds_24 !== null ? match.away_odds_24 * (1 + awayVol) : null,
      away_odds_48_min: match.away_odds_48 !== null ? match.away_odds_48 * (1 - awayVol) : null,
      away_odds_48_max: match.away_odds_48 !== null ? match.away_odds_48 * (1 + awayVol) : null,
      away_odds_72_min: match.away_odds_72 !== null ? match.away_odds_72 * (1 - awayVol) : null,
      away_odds_72_max: match.away_odds_72 !== null ? match.away_odds_72 * (1 + awayVol) : null,
      away_odds_167_min: match.away_odds_167 !== null ? match.away_odds_167 * (1 - awayVol) : null,
      away_odds_167_max: match.away_odds_167 !== null ? match.away_odds_167 * (1 + awayVol) : null
    }
    
    // 构造比赛明细请求参数
    const matchDetailsRequestData = {
      ...sameOddsRequestData,
      matchtime_e: match.matchtime ? (() => {
        const date = new Date(match.matchtime.split('T')[0]);
        date.setDate(date.getDate() - 1);
        return date.toISOString().split('T')[0];
      })() : null,
      // 添加积分范围参数
      home_avg_points_min: homeAvgPointsMin.value,
      home_avg_points_max: homeAvgPointsMax.value,
      away_avg_points_min: awayAvgPointsMin.value,
      away_avg_points_max: awayAvgPointsMax.value,
      // 添加信号值范围参数
      signal_home_initial_min: signalHomeMin.value,
      signal_home_initial_max: signalHomeMax.value,
      signal_draw_initial_min: signalDrawMin.value,
      signal_draw_initial_max: signalDrawMax.value,
      signal_away_initial_min: signalAwayMin.value,
      signal_away_initial_max: signalAwayMax.value,
      current_page: 1,
      page_size: 100
    }
    
    // 查询比赛明细数据
    const matchDetailsResponse = await getSameOddsMatchDetailsApi(matchDetailsRequestData)
    
    // 根据比赛明细数据计算同赔分析结果
    if (matchDetailsResponse.code === 0 && matchDetailsResponse.data) {
      matchDetailsData.value = matchDetailsResponse.data
      
      // 计算同赔分析统计结果
      const data = matchDetailsResponse.data
      const total_matches = data.length
      let home_wins = 0
      let draws = 0
      let away_wins = 0
      
      // 用于统计比分出现次数
      const scoreCounts: Record<string, number> = {}
      const homeWinScoreCounts: Record<string, number> = {} // 主胜比分统计
      const awayWinScoreCounts: Record<string, number> = {} // 客胜比分统计
      
      // 遍历所有比赛数据进行统计
      for (const match of data) {
        // 统计胜负平结果
        if (match.homescore !== null && match.awayscore !== null) {
          const score = `${match.homescore}-${match.awayscore}`
          scoreCounts[score] = (scoreCounts[score] || 0) + 1
          
          if (match.homescore > match.awayscore) {
            home_wins++
            // 主胜比分统计
            homeWinScoreCounts[score] = (homeWinScoreCounts[score] || 0) + 1
          } else if (match.homescore === match.awayscore) {
            draws++
          } else {
            away_wins++
            // 客胜比分统计
            awayWinScoreCounts[score] = (awayWinScoreCounts[score] || 0) + 1
          }
        }
      }
      
      // 计算胜率
      const home_win_rate = total_matches > 0 ? (home_wins / total_matches) * 100 : 0
      const draw_rate = total_matches > 0 ? (draws / total_matches) * 100 : 0
      const away_win_rate = total_matches > 0 ? (away_wins / total_matches) * 100 : 0
      
      // 找出最常见的三个比分
      const sortedScores = Object.entries(scoreCounts)
        .sort((a, b) => b[1] - a[1])
      
      const most_common_score = sortedScores[0] ? sortedScores[0][0] : null
      const second_most_common_score = sortedScores[1] ? sortedScores[1][0] : null
      const third_most_common_score = sortedScores[2] ? sortedScores[2][0] : null
      
      // 找出主胜的三个常见比分
      const sortedHomeWinScores = Object.entries(homeWinScoreCounts)
        .sort((a, b) => b[1] - a[1]);
      
      const home_win_most_common_score = sortedHomeWinScores[0] ? sortedHomeWinScores[0][0] : null;
      const home_win_second_most_common_score = sortedHomeWinScores[1] ? sortedHomeWinScores[1][0] : null;
      const home_win_third_most_common_score = sortedHomeWinScores[2] ? sortedHomeWinScores[2][0] : null;
      
      // 找出客胜的三个常见比分
      const sortedAwayWinScores = Object.entries(awayWinScoreCounts)
        .sort((a, b) => b[1] - a[1]);
      
      const away_win_most_common_score = sortedAwayWinScores[0] ? sortedAwayWinScores[0][0] : null;
      const away_win_second_most_common_score = sortedAwayWinScores[1] ? sortedAwayWinScores[1][0] : null;
      const away_win_third_most_common_score = sortedAwayWinScores[2] ? sortedAwayWinScores[2][0] : null;
      
      // 构造同赔分析结果
      sameOddsAnalysisResult.value = {
        total_matches,
        home_wins,
        draws,
        away_wins,
        home_win_rate,
        draw_rate,
        away_win_rate,
        most_common_score,
        second_most_common_score,
        third_most_common_score,
        home_win_most_common_score,
        home_win_second_most_common_score,
        home_win_third_most_common_score,
        away_win_most_common_score,
        away_win_second_most_common_score,
        away_win_third_most_common_score
      }
      
      ElMessage.success('同赔分析查询成功')
    } else {
      matchDetailsData.value = []
      ElMessage.error(matchDetailsResponse.message || '获取比赛明细数据失败')
    }
    
    // 处理比赛明细数据
    if (matchDetailsResponse.code === 0 && matchDetailsResponse.data) {
      matchDetailsData.value = matchDetailsResponse.data
    } else {
      matchDetailsData.value = []
      ElMessage.error(matchDetailsResponse.message || '获取比赛明细数据失败')
    }
  } catch (error) {
    console.error('查询同赔分析失败:', error)
    ElMessage.error('查询同赔分析失败，请稍后重试')
  } finally {
    sameOddsAnalysisLoading.value = false
    matchDetailsLoading.value = false
  }
}

// 查询爆冷分析
async function fetchColdPlayAnalysis() {
  if (!currentMatchForAnalysis.value) {
    return
  }
  
  // 检查必要的参数是否存在
  const match = currentMatchForAnalysis.value
  if (!match.homeid || !match.awayid || !match.matchtime || !match.season_id) {
    console.warn('缺少必要的参数进行爆冷分析:', {
      homeid: match.homeid,
      awayid: match.awayid,
      matchtime: match.matchtime,
      season_id: match.season_id
    })
    // 如果缺少必要参数，不执行爆冷分析
    return
  }
  
  coldPlayAnalysisLoading.value = true
  
  try {
    // 获取主队爆冷分析数据
    const homeRequestData = {
      teamid: match.homeid,
      match_date: match.matchtime ? match.matchtime.split('T')[0] : null,
      season_id: match.season_id
    }
    
    // 获取客队爆冷分析数据
    const awayRequestData = {
      teamid: match.awayid,
      match_date: match.matchtime ? match.matchtime.split('T')[0] : null,
      season_id: match.season_id
    }
    
    // 并行请求主队和客队的爆冷分析数据
    const [homeResponse, awayResponse] = await Promise.all([
      getColdPlayAnalysisStatsApi(homeRequestData),
      getColdPlayAnalysisStatsApi(awayRequestData)
    ])
    
    if (homeResponse.code === 0 && awayResponse.code === 0) {
      coldPlayAnalysisData.value = {
        home: homeResponse.data,
        away: awayResponse.data
      }
    } else {
      const errorMessage = homeResponse.message || awayResponse.message || '获取爆冷分析数据失败'
      ElMessage.error(errorMessage)
    }
  } catch (error) {
    console.error('查询爆冷分析失败:', error)
    ElMessage.error('查询爆冷分析失败，请稍后重试')
  } finally {
    coldPlayAnalysisLoading.value = false
  }
}

// 更新标签页标题
function updateTabTitle(newMatch: HistoricalSameOddsData) {
  if (newMatch && newMatch.homesxname && newMatch.awaysxname) {
    const homeScore = newMatch.homescore !== null ? newMatch.homescore : '-'
    const awayScore = newMatch.awayscore !== null ? newMatch.awayscore : '-'
    const title = `同赔分析-${newMatch.homesxname} ${homeScore} - ${awayScore} ${newMatch.awaysxname}`
    
    // 设置浏览器标题
    document.title = title
    
    // 更新 tags-view store 中的标题
    const visitedViews = tagsViewStore.visitedViews
    const currentRoutePath = route.path
    const index = visitedViews.findIndex(view => view.path === currentRoutePath)
    
    if (index !== -1) {
      // 更新 visitedViews 中的标题
      visitedViews[index].meta = {
        ...visitedViews[index].meta,
        title: title
      }
      // 触发响应式更新
      tagsViewStore.visitedViews = [...visitedViews]
    }
  }
}

// 监听currentMatchForAnalysis变化，动态更新路由标题
watch(currentMatchForAnalysis, (newMatch) => {
  if (newMatch && newMatch.homesxname && newMatch.awaysxname) {
    updateTabTitle(newMatch)
  }
}, { immediate: true })

// 从URL参数中获取比赛数据
function getMatchFromUrlParams(): HistoricalSameOddsData | null {
  // 在 hash 路由模式下，需要从 hash 中提取查询参数
  const hash = window.location.hash
  const queryString = hash.includes('?') ? hash.split('?')[1] : ''
  const params = new URLSearchParams(queryString)
  
  // 检查必要参数是否存在
  const fid = params.get('fid')
  const homesxname = params.get('homesxname')
  const awaysxname = params.get('awaysxname')
  
  if (!fid || !homesxname || !awaysxname) {
    return null
  }
  
  return {
    fid: parseInt(fid) || null,
    event_name: params.get('event_name') || null,
    homesxname: homesxname,
    awaysxname: awaysxname,
    matchtime: params.get('matchtime') || null,
    homescore: params.get('homescore') ? parseInt(params.get('homescore')!) : null,
    awayscore: params.get('awayscore') ? parseInt(params.get('awayscore')!) : null,
    home_odds_0: parseFloat(params.get('home_odds_0') || '0') || null,
    home_odds_24: parseFloat(params.get('home_odds_24') || '0') || null,
    home_odds_48: parseFloat(params.get('home_odds_48') || '0') || null,
    home_odds_72: parseFloat(params.get('home_odds_72') || '0') || null,
    home_odds_167: parseFloat(params.get('home_odds_167') || '0') || null,
    draw_odds_0: parseFloat(params.get('draw_odds_0') || '0') || null,
    draw_odds_24: parseFloat(params.get('draw_odds_24') || '0') || null,
    draw_odds_48: parseFloat(params.get('draw_odds_48') || '0') || null,
    draw_odds_72: parseFloat(params.get('draw_odds_72') || '0') || null,
    draw_odds_167: parseFloat(params.get('draw_odds_167') || '0') || null,
    away_odds_0: parseFloat(params.get('away_odds_0') || '0') || null,
    away_odds_24: parseFloat(params.get('away_odds_24') || '0') || null,
    away_odds_48: parseFloat(params.get('away_odds_48') || '0') || null,
    away_odds_72: parseFloat(params.get('away_odds_72') || '0') || null,
    away_odds_167: parseFloat(params.get('away_odds_167') || '0') || null,
    // 爆冷分析需要的字段
    season_id: params.get('season_id') ? parseInt(params.get('season_id')!) : null,
    homeid: params.get('homeid') ? parseInt(params.get('homeid')!) : null,
    awayid: params.get('awayid') ? parseInt(params.get('awayid')!) : null,
    order_num: params.get('order_num') || null,
    ownerdate: params.get('ownerdate') || null,
    home_avg_points: params.get('home_avg_points') ? parseFloat(params.get('home_avg_points')!) : null,
    away_avg_points: params.get('away_avg_points') ? parseFloat(params.get('away_avg_points')!) : null,
    signal_home_initial: params.get('signal_home_initial') ? parseFloat(params.get('signal_home_initial')!) : null,
    signal_draw_initial: params.get('signal_draw_initial') ? parseFloat(params.get('signal_draw_initial')!) : null,
    signal_away_initial: params.get('signal_away_initial') ? parseFloat(params.get('signal_away_initial')!) : null
  }
}

// 生命周期
onMounted(() => {
  // 优先从URL参数中获取比赛数据
  let matchData = getMatchFromUrlParams()
  
  // 如果URL参数中没有数据，尝试从store中获取
  if (!matchData) {
    matchData = currentMatchForAnalysis.value
  }
  
  if (!matchData) {
    ElMessage.error('缺少比赛数据')
    goBack()
    return
  }
  
  // 设置当前比赛数据
  currentMatchForAnalysis.value = matchData
  
  // 页面加载时自动查询爆冷分析数据
  fetchColdPlayAnalysis()
  
  // 计算并设置初始波动率
  nextTick(() => {
    const homeRate = getVolatilityRate(selectedMatchOdds.value.home) * 100
    const drawRate = getVolatilityRate(selectedMatchOdds.value.draw) * 100
    const awayRate = getVolatilityRate(selectedMatchOdds.value.away) * 100
    
    // 设置初始波动率，确保在有效范围内
    homeVolatility.value = Math.max(1, Math.min(20, parseFloat(homeRate.toFixed(2))))
    drawVolatility.value = Math.max(1, Math.min(20, parseFloat(drawRate.toFixed(2))))
    awayVolatility.value = Math.max(1, Math.min(20, parseFloat(awayRate.toFixed(2))))
  })
})
</script>

<style scoped>
.same-odds-analysis-page {
  padding: 20px;
}

.title-card {
  margin-bottom: 20px;
}

.page-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
  font-weight: bold;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.odds-range-card {
  margin-bottom: 20px;
}

.volatility-row {
  margin-bottom: 20px;
}

.volatility-control {
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.volatility-info {
  margin-bottom: 10px;
  padding: 8px;
  background-color: #e3f2fd;
  border-radius: 4px;
  font-size: 12px;
}

.volatility-range {
  margin: 2px 0;
  color: #1976d2;
  font-weight: 500;
}

.volatility-slider {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-top: 10px;
}

.volatility-stepper {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 10px;
}

.volatility-label {
  font-size: 14px;
  color: #606266;
  min-width: 60px;
}

.volatility-value {
  font-size: 14px;
  font-weight: bold;
  color: #409eff;
  min-width: 40px;
  text-align: right;
}

.odds-range-content h4 {
  margin: 0 0 10px 0;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.odds-range-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  padding: 4px 0;
}

.odds-label {
  width: 80px;
  font-size: 12px;
  color: #606266;
}

.odds-value {
  width: 60px;
  font-weight: bold;
  color: #303133;
  text-align: center;
}

.odds-range {
  flex: 1;
  font-size: 12px;
  color: #909399;
  margin-left: 10px;
}

.query-button-wrapper {
  text-align: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.analysis-result-card {
  margin-top: 20px;
}

.analysis-result-content {
  padding: 10px 0;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.rate-row {
  margin-bottom: 20px;
}

.rate-item {
  text-align: center;
  padding: 15px;
  border-radius: 8px;
}

.rate-item.home {
  background-color: #f0f9ff;
  border: 1px solid #bfdbfe;
}

.rate-item.draw {
  background-color: #fef3c7;
  border: 1px solid #fde68a;
}

.rate-item.away {
  background-color: #f0fdf4;
  border: 1px solid #bbf7d0;
}

.rate-value {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 5px;
}

.rate-item.home .rate-value {
  color: #1e40af;
}

.rate-item.draw .rate-value {
  color: #92400e;
}

.rate-item.away .rate-value {
  color: #166534;
}

.rate-label {
  font-size: 14px;
  color: #606266;
}

.score-row {
  margin-bottom: 20px;
}

.score-item {
  text-align: center;
  padding: 15px;
  background-color: #fafafa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.score-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.score-value {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.cold-play-analysis-card {
  margin-top: 5px;
}

.team-analysis {
  padding: 10px;
}

.team-analysis.home {
  border-right: 1px solid #ebeef5;
}

.team-title {
  text-align: center;
  margin: 10px 0;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.table-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.cell-label {
  font-size: 12px;
  color: #606266;
  margin-bottom: 2px;
}

.cell-value {
  font-size: 14px;
  font-weight: bold;
  color: #303133;
}

/* 赔率显示样式 */
.odds-group {
  display: flex;
  gap: 8px;
}

.odds-item {
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.odds-item.home {
  background-color: #f0f9ff;
  color: #1e40af;
}

.odds-item.draw {
  background-color: #fef3c7;
  color: #92400e;
}

.odds-item.away {
  background-color: #f0fdf4;
  color: #166534;
}

/* 积分和信号值范围输入样式 */
.range-inputs-row {
  margin-bottom: 5px;
}

.range-input-group {
  padding: 5px;
  background-color: #f8f9fa;
  border-radius: 2px;
  border: 1px solid #e9ecef;
  margin-bottom: 5px;
}

.range-input-group.compact {
  padding: 5px;
}

.range-input-group h4 {
  margin: 0 0 5px 0;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.range-input-group.compact h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  text-align: center;
}

.range-separator {
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  color: #606266;
}
</style>
